#include "ArchivoDocumentos.h"

ArchivoDocumentos::ArchivoDocumentos(const char* filename):Archivo((string(Archivo::indexDir)).append(filename).c_str()) {
    string s1 = (string(Archivo::indexDir)).append(filename);
    string s2 = s1.substr(0, s1.length() - 4);
    s2 += ".ind";

    this->i = new IndiceDocumentos(s2.c_str());
}

void ArchivoDocumentos::setHeader(string pathRaiz) {
    char* s = new char[pathRaiz.length() + 1];
    strcpy(s, pathRaiz.c_str());

    unsigned short int numBytes = strlen(s);

    this->write((char*) &numBytes, sizeof(unsigned short int));
    this->write((char*) s, numBytes);
    delete[] s;
}

void ArchivoDocumentos::add(uint32_t nroDoc, string path) {    
    unsigned char size = (unsigned char) path.size();

    i->add(nroDoc, (uint32_t) this->tellp());

    char* s = new char[path.size() + 1];
    strcpy(s, path.c_str());

    this->write((char*) &size, sizeof(unsigned char));
    this->write((char*) &nroDoc, sizeof(uint32_t));
    this->write((char*) s, strlen(s));

    delete[] s;
}

string ArchivoDocumentos::getPath(uint32_t nroDoc) {
    this->clear();

    this->seekg((unsigned)i->getOffset(nroDoc), ios::beg);

    uint32_t doc;
    unsigned char size;
    this->read((char*) &size, sizeof(unsigned char));

    char* str = new char[size + 1];
    this->read((char*) &doc, sizeof(uint32_t));
    this->read((char*) str, size);

    str[size] = '\0';
    string s = string(str);
    delete[] str;

    return s;
}

string ArchivoDocumentos::getPathRaiz() {
    this->clear();

    this->seekg(0, ios::beg);

    unsigned short int numBytes;
    this->read((char*) &numBytes, sizeof(unsigned short int));

    char* pathRaiz = new char[numBytes + 1];
    this->read((char*) pathRaiz, numBytes);
    pathRaiz[numBytes] = '\0';

    string s(pathRaiz);
    return s;
}

ArchivoDocumentos::~ArchivoDocumentos() {
    delete (this->i);
    this->close();
}
